package com.loto.webapp.action;

import org.apache.struts2.ServletActionContext;

import com.loto.webapp.bo.UserBo;
import com.loto.webapp.util.Constants;
import com.loto.webapp.util.Files;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {

	private static final long serialVersionUID = 1L;

	private UserBo userBo;

	private String username;

	private String password;

	public void validate() {
		clearErrorsAndMessages();
		if (username == null || username.equals("")) {
			addFieldError("username", getText("login.error.username"));
		}
		if (password == null || password.equals("")) {
			addFieldError("password", getText("login.error.password"));
		}
	}

	public String execute() throws Exception {
		if (this.userBo.login(username, password)) {
			ActionContext.getContext().getSession()
					.put(Constants.USERNAME_KEY, username);
			Files.setMenuCache(ServletActionContext.getRequest(), username);
			return Action.SUCCESS;
		} else {
			super.addActionError(getText("login.message.failed"));
			return Action.INPUT;
		}
	}

	public UserBo getUserBo() {
		return userBo;
	}

	public void setUserBo(UserBo userBo) {
		this.userBo = userBo;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

}
